package com.mocha.bss.domain.rbac.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.mocha.bss.domain.rbac.repository.MochaRoleRepository;
import com.mocha.bss.domain.rbac.repository.MochaRoleSensitiveRepository;
import com.mocha.bss.domain.rbac.repository.entity.RoleEntity;
import com.mocha.bss.domain.rbac.repository.entity.RoleSensitiveEntity;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: songkui
 * @since: 2023/4/12 13:55
 */
@Service
@Slf4j
@AllArgsConstructor
public class MochaRoleSensitiveService {

    private final MochaRoleSensitiveRepository mochaRoleSensitiveRepository;
    private final MochaRoleRepository mochaRoleRepository;


    /**
     * TODO 在更改 角色  和  敏感词 关系 时候 需要调用
     * TODO 注意并非问题； 因为接受方有一个 判断是否更新
     * 2，调用远程刷新需要用到的服务；
     */
    //public void flushRPCRoleSensitiveMap(){
    //    rpcHandler.sensitiveServerAPI();
    //
    //}

    public Map<String, String> getRoleSensitiveMap(){
        Map<String, List<RoleSensitiveEntity>> map = findAllByRoleCodeTOList();
        if (CollectionUtil.isEmpty(map)){
            return null;
        }

        Map<String, String> roleMap = new HashMap<>();
        map.forEach((k, v) ->{
            if (CollectionUtil.isNotEmpty(v)){
                roleMap.put(k,  StrUtil.join(",", v.stream().map(RoleSensitiveEntity::getSensitiveType).collect(Collectors.toList())));
            }
        });

        return roleMap;

    }

    private Map<String, List<RoleSensitiveEntity>> findAllByRoleCodeTOList(){

        List<RoleSensitiveEntity> list = mochaRoleSensitiveRepository.list();
        if (CollectionUtil.isEmpty(list)){
            return null;
        }
        List<RoleEntity> roleList = mochaRoleRepository.findRolesByAll();
        Map<Integer, List<RoleSensitiveEntity>> map = list.stream().collect(Collectors.groupingBy(RoleSensitiveEntity::getRoleId));

        Map<String, List<RoleSensitiveEntity>> resMap = new HashMap<>();
        map.forEach((k,v) ->{
            RoleEntity roleEntity = roleList.stream().filter(r -> k.intValue() == r.getId().intValue()).findAny().orElse(null);
            if (null != roleEntity){
                resMap.put(roleEntity.getRoleCode(), v);
            }
        });
        return resMap;
    }



}
